import axios from 'axios';
import { ElMessage } from 'element-plus';
const CancelToken = axios.CancelToken;
axios.defaults.timeout = 120000;

class request {
  cancel: any;
  constructor() {}
  _checkStatus(status: number) {
    if (status === 401) {
      window.location.href = '';
      return;
    }
    return this;
  }

  _checkParams(params: any) {
    if (!params || !params.url) {
      throw new Error("request'url is missed!");
    }
    return this;
  }

  _getHeaders(header: any) {
    let headers: any = {};
    let userToken: string = localStorage['token'];
    // 如果 sessionStorage有token就优先用session的
    if (sessionStorage['token']) {
      userToken = sessionStorage['token'];
    }
    if (userToken) {
      headers['token'] = userToken;
    }
    if (header) {
      for (let key in header) {
        headers[key] = header[key];
      }
    }
    return headers;
  }

  _defaultParamsCallback(response: any, params: any) {
    response
      .then(function (res: any) {
        let data = res.data;

        if (data && data.err) {
          console && console.error(data.err);
        }
        if (data.message && data.message.length > 200) {
          console && console.error(data.message);
          data.message = '操作异常，请稍后重试';
        }
        params.done && params.done(res.data);
      })
      .catch(function (err: any) {
        if (!err) {
          params.fail && params.fail('can not catch error!');
        } else {
          if (err.response) {
            if (err.response.status === 401) {
              ElMessage.error('权限不足');

              params.fail && params.fail(err);
              return response;
            }
            params.fail && params.fail(err);
          } else if (err.message) {
            params.fail && params.fail(err);
          }
        }
      });
    return response;
  }

  _request({ url, method, params = {}, data = {}, baseURL, header }: any) {
    const headers = this._getHeaders(header);
    return axios.request({
      method,
      baseURL,
      url,
      params,
      data,
      headers,
      cancelToken: new CancelToken(c => {
        // 强行中断请求要用到的
        this.cancel = c;
      }),
      validateStatus: status => {
        this._checkStatus(status);
        return status >= 200 && status <= 500 && status !== 404 && status !== 401;
      },
    });
  }

  post(params: any) {
    const res = this._checkParams(params)._request({
      method: 'post',
      url: params.url,
      data: params.data,
      header: params.header,
      baseURL: '',
    });

    return this._defaultParamsCallback(res, params);
  }
  get(params: any) {
    const res = this._checkParams(params)._request({
      method: 'get',
      url: params.url,
      params: params.data,
      header: params.header,
      baseURL: '',
    });

    return this._defaultParamsCallback(res, params);
  }

  checkLogin() {
    return localStorage['token'] && this._checkStatus(401);
  }
}

export default new request();
